package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;
    @Autowired
    WmMaterialMapper wmMaterialMapper;

    @Override
    public ResponseResult upload(MultipartFile file) {
        //1.校验参数
        if(file==null || file.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传minio
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String originalFilename = file.getOriginalFilename();//文件原始名称
        int index = originalFilename.lastIndexOf(".");
        String fileName = null;
        if(index>0){
            String suffix = originalFilename.substring(index);//后缀
            fileName= uuid+suffix;
        }
        String uploadImgFile=null;
        try {
            uploadImgFile = fileStorageService.uploadImgFile(null, fileName, file.getInputStream());
            log.info("图片在minio的访问路径:  {}", uploadImgFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }

        //3.保存素材信息到db
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(uploadImgFile);
        wmMaterial.setType((short)0);
        wmMaterial.setIsCollection((short)0);
        wmMaterialMapper.insert(wmMaterial);

        //4.返回
        return ResponseResult.okResult(wmMaterial);
    }


    @Override
    public ResponseResult list(WmMaterialDto dto) {
        //1.校验
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        if(dto.getIsCollection()==null || dto.getIsCollection()>1 || dto.getIsCollection()<0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.分页条件查询
        IPage<WmMaterial> pageParam = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        if(dto.getIsCollection()==1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());// where is_collection = 1
        }
        //每个自媒体人 只查自己的素材
        wrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());// where user_id= xxx
        //按创建时间倒序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);// order by created_time desc

        IPage<WmMaterial> page = this.page(pageParam, wrapper);

        //3.封装结果返回
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
//        return ResponseResult.okResult(pageResponseResult);//错误， 直接返回pageResponseResult即可
        return pageResponseResult;
    }


    @Override
    public ResponseResult del(Integer id) {
        //1.校验
        if(id==null || id<0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = this.getById(id);
        if(wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //校验当前id对象的素材是不是当前登录人的素材
        Integer userId = WmThreadLocalUtil.getUser().getId();
        if(userId==null || !userId.equals(wmMaterial.getUserId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        //2.删除
        this.removeById(id);

        //3.返回
        return ResponseResult.okResult("删除成功");
    }

    /**
     *
     * @param collectMaterial 1收藏   0取消收藏
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectOrCancelCollect(Short collectMaterial, Integer id) {
        //1.校验
        if(id==null || id<0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = this.getById(id);
        if(wmMaterial==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //校验当前id对象的素材是不是当前登录人的素材
        Integer userId = WmThreadLocalUtil.getUser().getId();
        if(userId==null || !userId.equals(wmMaterial.getUserId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }


        //2.修改
        wmMaterial.setIsCollection(collectMaterial);
        this.updateById(wmMaterial);

        //3.返回
        return ResponseResult.okResult("操作成功");
    }
}
